﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using SoftwareLogistics.SharepointClient.Library.Models;
using System.Security;
using System.Net.Browser;
using SoftwareLogistics.SharepointClient.Library;

namespace SoftwareLogistics.SharepointClient
{
    public class SPAuth
    {
        public List<SPUser> Users { get; set; }

        public event EventHandler Authenticated;
        public event EventHandler FailedAuthentication;

        const string PostXML = @"<s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"">
    <s:Body>
        <Login xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.microsoft.com/sharepoint/soap/"">
            <username>{0}</username>
            <password>{1}</password>
        </Login>
    </s:Body>
</s:Envelope>";

        CookieContainer _cookieJar = new CookieContainer();

        public CookieContainer GetCookieJar
        {
            get
            {
                return _cookieJar;
            }
        }

        public void Auth(string userName, string password)
        {
            var request = WebRequestCreator.ClientHttp.Create(Common.SPAuthUri) as HttpWebRequest;

            request.CookieContainer = _cookieJar;

            request.Method = "POST";
            request.ContentType = "text/xml; charset=utf-8";
            request.Headers["Cache-Control"] = "no-cache";
            request.Headers["Pragma"] = "no-cache";
            request.Headers["SOAPAction"] = "http://schemas.microsoft.com/sharepoint/soap/Login";
                        
            request.BeginGetRequestStream((async) =>
            {
                var stream = request.EndGetRequestStream(async);
                using (var writer = new StreamWriter(stream))
                {
                    writer.Write(String.Format(PostXML, userName, password));
                }

                request.BeginGetResponse((respCallback) =>
                {
                    try
                    {
                        var response = request.EndGetResponse(respCallback) as HttpWebResponse;

                        var cookies = response.Cookies;
                        var cookie = response.Headers["Set-Cookie"];

                        Authenticated(this, null);
                    }
                    catch (Exception exc)
                    {
                        Debug.WriteLine(exc.Message);
                        FailedAuthentication(this, null);
                    }

                }, null);
            }, null);
        }
    }
}
